/*This file is part of WZLibCP.

 *  WZLibCP is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

 *  WZLibCP is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
    along with WZLibCP.  If not, see <http://www.gnu.org/licenses/>.
		
	Author: calc0000
*/
#include "stdafx.h"
#include "WZDirectory.h"

#include "WZFileHeader.h"
#include "WZImage.h"

using namespace std;

namespace WZLib{
	WZObjectCollection&		WZDirectory::subDirs(){return this->_subDirs;}
	WZObjectCollection&		WZDirectory::childImages(){return this->_childImages;}
	int&					WZDirectory::blockSize(){return this->_blockSize;}
	int&					WZDirectory::checksum(){return this->_checksum;}
	unsigned int&			WZDirectory::offset(){return this->_offset;}
	ctor WZDirectory::WZDirectory(string name):WZObject(name,WZObject::Directory){
	}
	dtor WZDirectory::~WZDirectory(){
		for(unsigned int i=0,l=this->_subDirs.size();i<l;i++)
			delete this->_subDirs[i];
		this->_subDirs.clear();
		for(unsigned int i=0,l=this->_childImages.size();i<l;i++)
			delete this->_childImages[i];
		this->_childImages.clear();
	}
	ErrorCode WZDirectory::parse(WZLib::WZBinaryReader *reader){
		int count=reader->ReadCompressedInt();
		for(int i=0;i<count;i++){
			byte type=reader->ReadByte();
			string name="";
			int fsize;
			int checksum;
			unsigned int offset;
			if(type==2){
				int stringOffset=reader->ReadInt32();
				long pos=reader->Position();
				if(reader->header==NULL)
					return Error_WZLib_HeaderNull;
				reader->Position(reader->header->fileStart()+stringOffset);
				type=reader->ReadByte();
				name=reader->ReadEncryptedString();
				reader->Position(pos);
			}else if(type==3 || type==4){
				name=reader->ReadEncryptedString();
			}else
				continue;
			fsize=reader->ReadCompressedInt();
			checksum=reader->ReadCompressedInt();
			offset=reader->ReadOffset();
			if(type==3){
				WZDirectory* dir=new WZDirectory(name);
				*(dir->parent())=this;
				dir->blockSize()=fsize;
				dir->checksum()=checksum;
				dir->offset()=offset;
				this->_subDirs.push_back(dir);
				long co=reader->Position();
				reader->Position(offset);
				dir->parse(reader);
				reader->Position(co);
			}else{
				WZImage* img=new WZImage(name);
				*(img->parent())=this;
				img->blockSize()=fsize;
				img->checksum()=checksum;
				img->offset()=offset;
				*(img->reader())=reader;
				this->_childImages.push_back(img);
			}
		}
		this->_parsed=true;
		return Error_NoError;
	}
};